#user information management
class ViewController < ApplicationController
  helper ReportHelper
  before_filter :authorize, :except =>[:viewcompany,:viewreport,:createcomment]
  
  verify :method => :post,:only =>[:savepic,:updateuser,:updateperson,:updatepassword,:createmessage], :session => :user_id,
  :redirect_to => { :action => :view }
  
  def index
    redirect_to :action=>"view"
  end
  
  def method_missing(name, *args) 
    render :template=>"index/null"
  end
   
  def view
    user_id = session[:user_id] || -1  
    if @user = User.find(user_id)
      @incumbents = @user.Incumbents
      @friends = @user.Friends
      @tomessages = @user.Tomessages
      @fmmessages = @user.Fmmessages
      @reports = @user.Reports
      render :layout => "/layouts/report"
    else
      session[:user_id]=nil
      redirect_to :controller=>'login',:action=> 'login'
    end
  rescue
    redirect_to :controller => "index"  
  end
  
  def viewuser
    id = params[:id] || -1  
    if @user =  User.find(id)
      @user.anonymous=false if @user.id==session[:user_id]
      render :template=>"/view/viewuser",:layout => "/layouts/report"
    end
  rescue
    redirect_to :controller => "index"
  end
  
  def viewmessage
    id = params[:id] || -1
    owner_id = session[:user_id] || -1
    @message = Message.find_by_id_and_owner_id(id,owner_id)
  rescue
    redirect_to :controller => "index"
  end
  
  def viewcompany
    id = params[:id] || -1
    if @company = Company.find_by_id(id,:include=>[:Comments])
      @company.update_attribute(:view_times,@company.view_times+1)
      @salary=Report.find(@company.coreport_id).aver_salary
    end
  rescue
    redirect_to :controller => "index"
  end
  
  def createcomment
    unless Validation.validate(session[:code],params[:validation])
      session[:code]=nil
      render :inline=>%{<script type="text/javascript">alert('请刷新页面后完成边上的算术题，谢谢！');
        document.getElementById('validation').src='<%= url_for(:controller=>"index",:action=>"postvalidation")%>';</script>}
    else
      if params[:comment][:title].length>30|| params[:comment][:title]==""
        render :inline=>%{<script type="text/javascript">alert('对不起，您的标题过长或者为空！')</script>}
      elsif params[:comment][:body]==""
        render :inline=>%{<script type="text/javascript">alert("对不起，您的评论内容不能为空！")</script>}
      else
        session[:code]=nil
        id = params[:id] || 0
        category = params[:category].to_i || 0
        user_id = session[:user_id] || 0
        comment = Comment.new(params[:comment])
        comment.created_time= Time.now
        comment.user_id= user_id
        comment.obj_id = id
        comment.category = category
        if category==1
          object=Incumbent.find(comment.obj_id)
        elsif category==2
          object=Report.find(comment.obj_id)
        else
          object=Company.find(comment.obj_id) 
        end
        if request.post? && comment.save
          object.update_attribute(:reply_times,object.reply_times+1)
          render_partial "/view/comment",comment
        end
      end
    end
  end
  
  def deletecomment
    id = params[:id] || -1
    user_id = session[:user_id] || -1
    comment=Comment.find_by_id_and_user_id(id,user_id)
    category = comment.category
    if category==1
      object=Incumbent.find(comment.obj_id)
    elsif category==2
      object=Report.find(comment.obj_id)
    else
      object=Company.find(comment.obj_id)    
    end
    object.update_attribute(:reply_times,object.reply_times-1) if comment.destroy
    render :partial => "/view/create_comment",:locals=>{:object=>object}
  end
  
  def modifycomment
    id = params[:id] || -1
    user_id = session[:user_id] || -1
    @comment=Comment.find_by_id_and_user_id(id,user_id)
    render :partial => "/view/modify_comment"
  end
  
  def updatecomment
    if params[:comment][:title].length>30
      render :inline=>%{<script type="text/javascript">alert('您的标题太长了！')</script>}
    else
      id = params[:id] || -1
      user_id = session[:user_id] || -1
      comment=Comment.find_by_id_and_user_id(id,user_id)
      comment.title=params[:comment][:title]
      comment.body=params[:comment][:body]
      comment.created_time= Time.now
      comment.save
      render :partial=>"/view/comment",:locals=>{:comment=>comment} if request.post? && comment.save
    end
  end
  
  def hidecomment
    id = params[:object_id] || -1
    category = params[:category]
    if category.to_i==1
      object=Incumbent.find(id)
    elsif category.to_i==3
      object=Company.find(id)
    elsif category.to_i==2
      object=Report.find(id) 
    else 
    end
    render :partial => "/view/create_comment",:locals=>{:object=>object}
  end
  
  def createfriend
    friend_id = params[:id] || -1
    owner_id = session[:user_id] || -1
    friend = Friend.new(:owner_id=>owner_id,
                        :friend_id=>friend_id,
                        :created_time=>Time.now)
    if thefriend=friend.Friend
      flash[:notice]=["<li>您已经将"+thefriend.name+"加为了您的好友了</li>"]
      friend.save
    else
      flash[:notice]=["<li>您无法将他/她加为您的好友了</li>"]
    end
    redirect_to :controller=>'view',:action=> 'viewuser',:id=>friend_id
  end
  
  def deletefriend
    id = params[:id] || -1
    owner_id = session[:user_id] || -1
    friend=Friend.find_by_id_and_owner_id(id,owner_id)
    friend.destroy if friend
  end
  
  def showmessage
    id = params[:id] || -1
    owner_id = session[:user_id] || -1
    if user=User.find(owner_id)
      message=Message.new(:owner_id=>owner_id,:torf_id=>id,:title=>"来自"+user.name+"的问候")
      render :partial => "create_message", :locals => {:object => message}
    else
      session[:user_id]=nil
      redirect_to :controller=>'login',:action=> 'login'
    end
  end
  
  def hidemessage
    render(:nothing => true)
  end
  
  
  def createmessage
    torf_id = params[:id] || -1
    owner_id = session[:user_id] || -1
    if user=User.find(owner_id)
      Message.create(:owner_id=>owner_id,:torf_id=>torf_id,:torf=>0,
                     :title=>params[:message][:title],:body=>params[:message][:body])
      Message.create(:owner_id=>torf_id,:torf_id=>owner_id,:torf=>1,
                     :title=>params[:message][:title],:body=>params[:message][:body])
      fmmessages = user.Fmmessages
      tomessages = user.Tomessages
      render :partial=>"message_list" , :locals => {:tomessages => tomessages, :fmmessages => fmmessages}
    else
      session[:user_id]=nil
      redirect_to :controller=>'login',:action=> 'login'
    end
  end
  
  def deletemessage
    id = params[:id] || -1
    owner_id = session[:user_id] || -1
    message=Message.find_by_id_and_owner_id(id,owner_id)
    message.destroy if message
  end
  
  def uploadpic
    # object=0 user
    @id=params[:id]
    @object=params[:object]
    render :layout=>false
  end
  
  def savepic
    id=params[:id]
    picture = Picture.new(params[:picture])
    picture.user_id = session[:user_id]
    object_id=params[:object].to_i
    oldpic = Picture.find(id)
    if object_id==0
      picture.User=User.find(picture.user_id)
    else
      picture.Company=Company.find(object_id)
    end  
    if picture.save
      oldpic.destroy if picture.user_id==oldpic.user_id
      flash[:notice]="<li>图片上传成功。</li>"
      redirect_to :controller=>"view",:action=>"uploadpic",:id=>picture.id, :object=>object_id
    else
      flash[:notice]="<li>图片格式不符，上传失败。</li>"
      redirect_to :controller=>"view",:action=>"uploadpic",:id=>id, :object=>object_id
    end
  rescue  
    flash[:notice]="<li>图片格式不符，上传失败。</li>"
    redirect_to :controller=>"view",:action=>"uploadpic",:id=>id, :object=>object_id
  end
  
  def hideuser
    render :inline =>%{<div align="right"><strong><%= link_to_remote "修改用户资料>>", :update=>"modifyuser", :url=>{:controller=>"view", :action=>"modifyuser", :id=>session[:user_id]} %></strong></div>}
  end
  
  def modifyuser
    user_id = session[:user_id] || -1
    if @user = User.find(user_id)
      render :partial => "modify_user", :locals => {:user => @user}
    else
      redirect_to :controller => "login", :action=>"login"
    end
  end
  
  def updateuser
    user_id = session[:user_id] || -1
    if user = User.find(user_id)
      owner=User.find_by_name(params[:user][:name])
      user.name=params[:user][:name] if owner==nil&&params[:user][:name]=~/[\d\w]+/&&params[:user][:name].length<20
      user.objects=params[:user][:objects] if params[:user][:objects].length<300
      user.interests=params[:user][:interests] if params[:user][:interests].length<300
      user.anonymous=params[:user][:anonymous]
      user.save
      render :partial=>"user_info",:locals => {:user => user}
    else
      redirect_to :controller => "login", :action=>"login"
    end
  rescue
    redirect_to :controller => "login", :action=>"login"
  end
  
  def hideperson
    render :inline =>%{<div align="right"><strong><%= link_to_remote "修改个人信息>>", :update=>"modifyperson", :url=>{:controller=>"view", :action=>"modifyperson", :id=>session[:user_id]} %></strong></div>}
  end
  
  def modifyperson
    user_id = session[:user_id] || -1
    @person = User.find(user_id).Person
    @person.texperience=@person.texperience.to_i
    render :partial => "modify_person", :locals => {:person => @person}
  rescue
    redirect_to :controller => "login", :action=>"login"
  end
  
  def updateperson
    user_id = session[:user_id] || -1
    user = User.find(user_id)
    person= user.Person
    updated=true
    birthday=Time.local(params[:person]["tbirthday(1i)"],params[:person]["tbirthday(2i)"],params[:person]["tbirthday(3i)"],0,0,0)
    unless params[:person][:name].length>20 || params[:person][:name]==person.name
      person.name= params[:person][:name]
      person.save
    end 
    params[:person][:tsex]= params[:person][:tsex]=="0" ? false : true
    unless person.tsex==params[:person][:tsex]
      person.tsex=params[:person][:tsex]
      updated=false
    end
    unless params[:person][:texperience].to_i==person.texperience
      person.texperience= params[:person][:texperience]
      updated=false
    end
    unless params[:person][:teducation_id].to_i==person.teducation_id
      person.teducation_id= params[:person][:teducation_id]
      updated=false
    end
    unless params[:person][:toversea_id].to_i==person.toversea_id
      person.toversea_id= params[:person][:toversea_id]
      updated=false
    end
    unless birthday==person.tbirthday
      person.tbirthday= birthday
      updated=false
    end
    unless updated
      person.updated=0
      person.save
    end
    render :partial=>"person_info",:locals => {:user => user}
  end
  
  def modifypassword
    render :layout=>false
  end
  
  def updatepassword
    user_id = session[:user_id] || -1
    user = User.find(user_id)
    if flash[:notice]=user.validate_password(params[:user][:old_password],params[:user][:new_password],params[:user][:confirm_password])
      redirect_to :controller=>"view",:action=>"modifypassword"
    else
      user.set_password(params[:user][:new_password])
      flash[:notice]="密码更新成功"
      redirect_to :controller=>"view",:action=>"modifypassword"
    end
  end
  
  def checkuser
    user_id = session[:user_id] || -1
    user = User.find(user_id)
    owner=User.find_by_name(params[:name])
    if params[:name]==""
      render :inline=>%{&nbsp;<script type="text/javascript">alert('注意，用户名不能为空');</script>}
    elsif owner==nil
      render :inline=>%{&nbsp;<script type="text/javascript">alert('恭喜，该用户名还未被注册');</script>}
    elsif owner.id==user.id
      render :inline=>%{&nbsp;<script type="text/javascript">alert('这是你的用户名哦！');</script>}
    else
      render :inline=>%{&nbsp;<script type="text/javascript">alert('对不起，该用户名已经存在了');</script>}
    end
  end
  
end
